DOUBAN.apikey = '0b16ea3a4078b7a42144beaec16a26ec';

var template_douban_subject = '<li class="g w0">\
									<h3 class="r">\
										<a class="l douban_link" target="_blank" href="${url}">${title}</a>\
									</h3>\
									<span >\
									评分:${rating}\
									</span>\
									<div class="g">\
									</div>\
									<span class="gl">\
									<a target="_blank" title="豆瓣详细信息" href="javascript:;" class="request_douban_info" data="${id}">More&nbsp;»</a>\
									</span>\
									<table class="verycd_info">\
									<tbody>\
										<tr>\
											<td class="inner-content" style="padding-left: 3em;">\
											</td>\
										</tr>\
									</tbody>\
									</table>\
									<span class="gl">\
									<a target="_blank" title="Verycd上的相关资源" href="javascript:;" class="request_verycd_resouces" data="${title}">Verycd相关资源&nbsp;»</a>\
									</span>\
								</li>\
								<div></div>',
	template_douban_info = '<table class="ts std">\
										<tbody>\
											<tr>\
												<td valign="top">\
													<img border="1"  alt="" src="${img}">\
												</td>\
												<td valign="top">\
													<div class="s">\
														${summary}\
														<b>...</b>\
													</div>\
												</td>\
											</tr>\
										</tbody>\
									</table>',
	template_verycd_topic = '<div style="padding-top: 0.75em;">\
								<a target="_blank" href="${url}" class="verycd_link">${title}</a><br>\
								${summary}<b>...</b><br>\
								<cite>${url}</cite>\
							 </div>',
	template_feed_entry =  ' <li class="g w0">\
								<h3 class="r">\
									<a class="l ${linkclass}" target="_blank" href="${url}"> ${title}</a>\
								</h3>\
								<div class="s" style="max-width:50em;padding-top:1em;">\
									${summary}<b>...</b><br>\
									<cite>${url}</cite>\
								</div>\
							</li>';
var ajaxloader = "<img src='/res/ajax-loader.gif'>";

function parseTpl(str,data){
	var result;
	for(var d in data){
		var data_v = '\\$\\{'+d+'\\}';
		str = str.replace(new RegExp(data_v,"g"),data[d]);
	}
	return str;		
}
String.prototype.parseTpl=function(data){return parseTpl(this,data);};

(function($){
	  $.extend({
	    jGFeed : function(url, fnk, num, key){
	      if(url == null) return false;
	      var gurl = "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&callback=?&q="+url;
	      if(num != null) gurl += "&num="+num;
	      if(key != null) gurl += "&key="+key;
	      $.getJSON(gurl, function(data){
	        if(typeof fnk == 'function')
			  fnk.call(this, data.responseData.feed);
			else
			  return false;
	      });
	    }
	  });
	})(jQuery);

function searchDouban(query,type,tag,start,count){
	var search = DOUBAN.searchMovies;
	if(type=='book'){
		search = DOUBAN.searchBooks;
	}else if(type=='music'){
		search =  DOUBAN.searchMusic;
	}
	search({
	    tag:tag,
	    keyword:query,
	    startindex:start,
	    maxresults:count,
	    callback:showDoubanResult
	});
}
function showDoubanResult(respon){
	var data = DOUBAN.parseSubjects(respon);
	if(data.totalResults>0){
		var html = "",len=data.entries.length;
		for(var i=0;i<len;i++){
			var tpl_data = {title:data.entries[i]['title'],
					url:data.entries[i]['link']['alternate'],
					id:data.entries[i]['id'],
					rating:''};
			if(data.entries[i]['rating']['average']>0){
				var r = Math.min(data.entries[i]['rating']['average'],10);
				var starclass = Math.round(r*10/2)-Math.round(r*10/2)%5
				if(starclass==0){
					starclass= 'bigstar00';
				}else{
					starclass= 'bigstar'+starclass;
				}
				
				tpl_data.rating = data.entries[i]['rating']['average']+'<span class="'+starclass+'"></span>';
			}
			//console.log(tpl_data);
			html += template_douban_subject.parseTpl(tpl_data);
		}
		$("#navcnt").show();
		$("#results_list").html(html);
	}else{
		$("#results_list").html('啥都没找到！');
	}
	//console.log(data);
}
function showDoubanSubject(subject,target){
//	console.log(subject);
	var tpl_data = {
			title:subject['title']||'',
			img:subject['link']['image']||'',
			summary:subject['summary']||''
			};
	if(subject['rating']['average']>0){
		var r = Math.min(subject['rating']['average'],10);
		var starclass = Math.round(r*10/2)-Math.round(r*10/2)%5
		if(starclass==0){
			starclass= 'bigstar00';
		}else{
			starclass= 'bigstar'+starclass;
		}
		
		tpl_data.rating = subject['rating']['average']+'<span class="'+starclass+'"></span>';
	}
	$(target).data('searchd',1);
	$(target).text('收缩').data('expand',1);
	$(target).parent().prev('div.g').html(template_douban_info.parseTpl(tpl_data));
//	console.log(target);
}
function showVerycdResources(resouces,target){
	//console.log(resouces);
	var len = resouces.entries.length,html="";
	if(len==0){
		html= '啥都没找到！';
	}else{
		for(var i=0;i<len;i++){
			var tpl_data = {
					title:resouces.entries[i]['title']||'',
					url:resouces.entries[i]['link']||'',
					summary:resouces.entries[i]['content']||''};
			html += template_verycd_topic.parseTpl(tpl_data);
		}
	}
	$(target).data('searchd',1);
	$(target).text('收缩').data('expand',1);
	$(target).parent().prev('.verycd_info').find('td.inner-content').html(html);
}
function requestDoubanSubject(target,id){
	$.getJSON(id+"?apikey=0b16ea3a4078b7a42144beaec16a26ec&alt=xd&callback=?", function(respon){
		var subject = DOUBAN.parseSubject(respon);
		showDoubanSubject(subject,target);
	});
}

function requestVerycdResouces(target,title){
	$.jGFeed(encodeURIComponent('http://www.verycd.com/search/folders?kw='+encodeURIComponent(title)+'&status=all&format=rss'),
			function(feeds){
			  if(!feeds){
			    return false;
			  }
			  showVerycdResources(feeds,target);
	}, 5);
}

function tabVerycdMovie(){
	$("#tbd div.tl-sel").removeClass('tl-sel');
	$("#hot_verycd_movie").parent().addClass('tl-sel');
	getHotFeed('http://verycd.com/sto/movie/feed','verycd_link');
}
function tabVerycdMusic(){
	$("#tbd div.tl-sel").removeClass('tl-sel');
	$("#hot_verycd_music").parent().addClass('tl-sel');
	getHotFeed('http://verycd.com/sto/music/feed','verycd_link');
}
function tabVerycdBook(){
	$("#tbd div.tl-sel").removeClass('tl-sel');
	$("#hot_verycd_book").parent().addClass('tl-sel');
	getHotFeed('http://verycd.com/sto/datum/feed','verycd_link');
}

function tabDoubanMovie(){
	$("#tbd div.tl-sel").removeClass('tl-sel');
	$("#hot_douban_movie").parent().addClass('tl-sel');
	getHotFeed('http://www.douban.com/feed/review/movie','douban_link');
}
function tabDoubanBook(){
	$("#tbd div.tl-sel").removeClass('tl-sel');
	$("#hot_douban_book").parent().addClass('tl-sel');
	getHotFeed('http://www.douban.com/feed/review/book','douban_link');
}
function tabDoubanMusic(){
	$("#tbd div.tl-sel").removeClass('tl-sel');
	$("#hot_douban_music").parent().addClass('tl-sel');
	getHotFeed('http://www.douban.com/feed/review/music','douban_link');
}
function getHotFeed(url,linkclass){
	$("#results_list").html(ajaxloader);
	$("#navcnt:visible").hide();
	$.jGFeed(encodeURIComponent(url),
			function(feeds){
			  if(!feeds){
			    return false;
			  }else{
				  var len = feeds.entries.length,html="";
					if(len==0){
						html= '啥都没找到！';
					}else{
						for(var i=0;i<len;i++){
							var tpl_data = {
									title:feeds.entries[i]['title']||'',
									url:feeds.entries[i]['link']||'',
									summary:feeds.entries[i]['content']||'',
									linkclass:linkclass||''};
							html += template_feed_entry.parseTpl(tpl_data);
						}
					}
					$("#results_list").html(html);
			  }
	}, 8);
}
$(function(){
	$.ajaxSetup({
		   cache:true
	 });
	$("#hot_verycd_movie").click(tabVerycdMovie);
	$("#hot_verycd_music").click(tabVerycdMusic);
	$("#hot_verycd_book").click(tabVerycdBook);
	$("#hot_douban_movie").click(tabDoubanMovie);
	$("#hot_douban_music").click(tabDoubanMusic);
	$("#hot_douban_book").click(tabDoubanBook);
	tabDoubanMovie();
	$("#tsf").submit(function(){
		var query = $("#query").val();
		if(/\S+/.test(query)){
			$("#tbd div.tl-sel").removeClass('tl-sel');
			$("#navcnt").hide();
			$("#results_list").html(ajaxloader);
			var type = $('input[name=type]:checked', '#tsf');
			if(type.length==1){
				searchDouban(query,type.val(),'',1,10)
			}
		}
		return false;
	});
	$("a.request_douban_info").live('click',function(){
		if($(this).data('searchd')!=1){
			$(this).parent().prev('div.g').html(ajaxloader);
			requestDoubanSubject(this,$(this).attr('data'));
		}else{
			if($(this).data('expand')!=1){
				$(this).data('expand',1);
				$(this).text('收缩');
				$(this).parent().prev('div.g').slideDown();
			}else{
				$(this).data('expand',0);
				$(this).text('展开');
				$(this).parent().prev('div.g').slideUp();
			}
		}
		return false;
	});
	$("a.request_verycd_resouces").live('click',function(){
		if($(this).data('searchd')!=1){
			$(this).parent().prev('.verycd_info').find('td.inner-content').html(ajaxloader);
			requestVerycdResouces(this,$(this).attr('data'));
		}else{
			if($(this).data('expand')!=1){
				$(this).data('expand',1);
				$(this).text('收缩');
				$(this).parent().prev('.verycd_info').slideDown();
			}else{
				$(this).data('expand',0);
				$(this).text('展开');
				$(this).parent().prev('.verycd_info').slideUp();
			}
		}
		return false;
	});
});